﻿
namespace n_ISPcommon
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

public static class ISPcommon
{
	//转换HEX文件数据为十六进制代码格式
	public static string SwitchCode( string Code )
	{
		Code = Code.TrimEnd( "\n\t ".ToCharArray() );
		string[] Lines = Code.Split( '\n' );
		StringBuilder TextBuffer = new StringBuilder( "" );
		string TextChar = null;
		
		int CAddress = 0;	//当前地址
		
		for( int i = 0; i < Lines.Length; ++i ) {
			//判断格式是否正确
			if( !Lines[ i ].StartsWith( ":" ) ) {
				MessageBox.Show( "HEX文件格式错误, 每条记录应该以字符':'开始" );
				return null;
			}
			string SLine = Lines[ i ];
			if( SLine.Length % 2 != 1 || SLine.Length < 11 ) {
				MessageBox.Show( "HEX文件格式错误, 当前记录的长度无效" );
				return null;
			}
			//读取当前记录的各个字段
			string DataLength = SLine.Substring( 1, 2 );
			string Address = SLine.Substring( 3, 4 );
			string Type = SLine.Substring( 7, 2 );
			string Data = SLine.Substring( 9, SLine.Length - 11 );
			string CheckSum = SLine.Substring( SLine.Length - 2, 2 );
			
			//判断记录长度是否合法
			int IdataLength = int.Parse( DataLength, System.Globalization.NumberStyles.HexNumber );
			if( IdataLength * 2 != Data.Length ) {
				MessageBox.Show( "HEX文件格式错误, 当前记录的长度无效: " + IdataLength + " " + DataLength );
				return null;
			}
			//判断校验和
			int IcheckSum = 0;
			for( int j = 1; j < SLine.Length; j += 2 ) {
				IcheckSum += int.Parse( SLine[ j ].ToString() + SLine[ j + 1 ], System.Globalization.NumberStyles.HexNumber );
				IcheckSum %= 256;
			}
			if( IcheckSum != 0 ) {
				MessageBox.Show( "HEX文件格式错误, 校验和出错: " + SLine );
				return null;
			}
			//判断是否结束记录
			if( Type == "01" ) {
				if( i != Lines.Length - 1 ) {
					MessageBox.Show( "HEX文件格式错误, 结束记录标志之后不能有记录" );
					return null;
				}
				break;
			}
			//忽略其他类型记录
			if( Type != "00" ) {
				continue;
			}
			//填充默认数据
			int IAddress = int.Parse( Address, System.Globalization.NumberStyles.HexNumber );
			while( CAddress < IAddress ) {
				TextChar += '.';
				TextBuffer.Append( " FF" );
				++CAddress;
				if( CAddress % 16 == 0 ) {
					TextBuffer.Append( "    " );
					TextBuffer.Append( TextChar );
					TextBuffer.Append( "\n" );
					TextChar = null;
				}
			}
			//填充实际数据
			int Index = 0;
			while( CAddress < IAddress + Data.Length / 2 ) {
				TextBuffer.Append( " " + Data[ Index ] + Data[ Index + 1 ] );
				int Value = int.Parse( Data[ Index ].ToString() + Data[ Index + 1 ], System.Globalization.NumberStyles.HexNumber );
				if( Value >= 32 && Value <= 126 ) {
					TextChar += (char)Value;
				}
				else {
					TextChar += '.';
				}
				Index += 2;
				++CAddress;
				if( CAddress % 16 == 0 ) {
					TextBuffer.Append( "    " );
					TextBuffer.Append( TextChar );
					TextBuffer.Append( "\n" );
					TextChar = null;
				}
			}
		}
		return TextBuffer.ToString();
	}
}
}
